package com.liuqi.knet.rpc.cluster;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * 负载均衡节点
 *
 * @author liuqi
 * @date 2024/6/20 10:41
 **/
public class LoadBalanceNode {

    private List<Node> nodes;

    public LoadBalanceNode() {
        this.nodes = new ArrayList<Node>();
    }

    public LoadBalanceNode(List<Node> nodes) {
        this.nodes = nodes;
    }

    public void addNode(InetSocketAddress remote) {
        addNode(remote, 1);
    }

    public void addNode(InetSocketAddress remote, int weight) {
        if (weight > 10 || weight < 1) {
            throw new IllegalArgumentException("集群节点权重仅支持[1 ~ 10]");
        }
        this.nodes.add(new Node(remote, weight));
    }

    /**
     * 等同于一个客户端
     */
    public static class Node {
        InetSocketAddress remote;
        int weight;     // 1 - 10
        public Node(InetSocketAddress remote, int weight) {
            this.remote = remote;
            this.weight = weight;
        }
        public InetSocketAddress getRemote() {
            return remote;
        }
        public int getWeight() {
            return weight;
        }
        @Override
        public String toString() {
            return "{" +
                    "remote=" + remote +
                    ", weight=" + weight +
                    '}';
        }
    }

    public List<Node> getNodes() {
        return nodes;
    }

    public void setNodes(List<Node> nodes) {
        this.nodes = nodes;
    }

    @Override
    public String toString() {
        return "LoadBalanceNode{" +
                "nodes=" + nodes +
                '}';
    }

}
